package controller

import (
	"gin-shop-admin/models"
	"gin-shop-admin/repository"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func GetManagers(c *gin.Context) {
	query, _ := c.GetQuery("query")
	page, pageOK := c.GetQuery("pageNum")
	limit, limitOK := c.GetQuery("pageSize")
	if !pageOK || !limitOK {
		c.JSON(201, gin.H{"msg": "参数获取失败"})
	}
	pageNum, _ := strconv.Atoi(page)
	pageSize, _ := strconv.Atoi(limit)
	total, managertList, err := repository.GetManagers(query, pageNum, pageSize)
	if err != nil {
		c.JSON(202, err)
		return
	} else {
		data := gin.H{
			"total": total,
			"listQuery": map[string]int{
				"pageNum":  pageNum,
				"pageSize": pageSize,
			},
			"list": managertList,
		}
		c.JSON(http.StatusOK, data)
		return
	}
}

func UpdateManagerState(c *gin.Context) {
	uid, uidOk := c.Params.Get("uid")
	state, stateOk := c.Params.Get("state")
	if !uidOk || !stateOk {
		c.JSON(201, gin.H{"msg": "接收参数uid或state失败"})
		return
	}
	err := repository.UpdateManagerState(uid, state)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "更新用户状态信息成功"})
	}
	return
}

func UpdateManagerRole(c *gin.Context) {
	uid, uidOK := c.Params.Get("uid")
	roleID, roleOK := c.GetPostForm("role_id")
	if !uidOK || !roleOK {
		c.JSON(201, gin.H{"msg": "获取参数失败"})
		return
	}
	mid, uid_err := strconv.Atoi(uid)
	role_id, role_err := strconv.Atoi(roleID)
	if uid_err != nil || role_err != nil {
		c.JSON(202, gin.H{"msg": "参数类型有误"})
	} else {
		err := repository.UpdateManagerRole(mid, role_id)
		if err != nil {
			c.JSON(203, gin.H{"msg": err})
		} else {
			c.JSON(http.StatusOK, gin.H{"msg": "修改成功"})
		}
	}
	return
}

func AddOneManager(c *gin.Context) {
	var manager models.Manager
	err := c.BindJSON(&manager)
	if err != nil {
		c.JSON(201, gin.H{"msg": "获取参数有误"})
		return
	}
	err = repository.InsertOneManagerr(&manager)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	} else {
		c.JSON(200, gin.H{"msg": "添加用户成功"})
	}
	return
}

func GetManager(c *gin.Context) {
	uid, ok := c.Params.Get("uid")
	if !ok {
		c.JSON(201, gin.H{"msg": "获取不到用户id"})
		return
	}
	manager, err := repository.GetManagerByID(uid)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "success", "data": manager})
	}
}

func UpdateManager(c *gin.Context) {
	var manager models.Manager
	err := c.BindJSON(&manager)
	if err != nil {
		c.JSON(201, gin.H{"msg": "获取参数有误"})
		return
	}
	err = repository.UpdateOneManager(&manager)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	} else {
		c.JSON(200, gin.H{"msg": "修改用户信息成功"})
	}
	return
}

func DeleteManager(c *gin.Context) {
	uid, ok := c.Params.Get("uid")
	if !ok {
		c.JSON(201, gin.H{"msg": "获取参数有误"})
		return
	}
	err := repository.DeleteManagerByID(uid)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	} else {
		c.JSON(200, gin.H{"msg": "删除用户成功"})
	}
	return
}
